//
//  EUPageJumpViewController.m
//
//  Created by WuJianNan on 11/21/14.
//  Copyright (c) 2014 nd.com.cn. All rights reserved.
//

#import "EUPageJumpViewController.h"
#import "EUPageJumpWebViewProgress.h"
#import "EUPageJumpWebViewProgressView.h"
#import "EUPageJump.h"

static id<EUPageJumpViewControllerDebugDelegate> debugDelegate;

@interface EUPageJumpViewController () <EUPageJumpWebViewProgressDelegate>
@property(nonatomic, strong) EUPageJumpWebViewProgress *progressProxy;
@property(nonatomic, strong) EUPageJumpWebViewProgressView *progressView;
@end

@implementation EUPageJumpViewController

+ (void)regisiterDebugDelegate:(id)delegate {
    debugDelegate = delegate;
}
- (id)initWithFromData:(NSDictionary *)fromData jumpControlDate:(NSDictionary *)jumpControlData {
    self = [self init];
    if (self) {
        self.fromData = fromData;
        self.jumpControlData = jumpControlData;
    }
    return self;
}

- (id)init {
    self = [super init];
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (self) {
    }
    return self;
}

- (NSString *)getCurrentPageID {
    return [NSString stringWithFormat:@"%lld", (long long)self];
}

#pragma mark - vc life cycle

- (void)viewDidLoad {
    //    self.wwwFolderName = [self getModulePathWithModuleId:self.ModuleId wwwFolderName:self.wwwFolderName];
    [super viewDidLoad];
    if (self.jumpControlData && self.jumpControlData[kControlTitleKey]) {
        self.title = self.jumpControlData[kControlTitleKey];
    }
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view setBackgroundColor:[UIColor colorWithRed:0.894 green:0.894 blue:0.894 alpha:1]];
    [self.webView setBackgroundColor:[UIColor colorWithRed:0.894 green:0.894 blue:0.894 alpha:1]];
    if (debugDelegate && [debugDelegate respondsToSelector:@selector(shouldShowWebViewProgressView:)]) {
        if ([debugDelegate shouldShowWebViewProgressView:self]) {
            [self setupProgressView];
        }
    }
    //自定义导航条等操作
    if (debugDelegate && [debugDelegate respondsToSelector:@selector(viewDidLoad:)]) {
        [debugDelegate viewDidLoad:self];
    }
    [self.webView.scrollView setScrollEnabled:YES];
    if ([[[UIDevice currentDevice] systemVersion] intValue] >= 7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        [self setNeedsStatusBarAppearanceUpdate];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    [self.navigationController.navigationBar setTranslucent:NO];

    //    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
    //        if ([[[UIDevice currentDevice] systemVersion] intValue] < 7) {
    //            [self.navigationController.navigationBar setBackgroundImage:[XGImage imageNamed:@"icx_navigation_background_-white"]
    //                                                          forBarMetrics:UIBarMetricsDefault];
    //        } else {
    //            [self.navigationController.navigationBar setBackgroundImage:[XGImage imageNamed:@"icx_navigation_background_-white"]
    //                                                          forBarMetrics:UIBarMetricsDefault];
    //        }
    //    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (debugDelegate && [debugDelegate respondsToSelector:@selector(didPageJumpViewControllerWillAppear:)]) {
        [debugDelegate didPageJumpViewControllerWillAppear:self];
    }
    [self fireCordovaViewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self fireCordovaWillDisappear:animated];
}

#pragma mark - 处理webview
- (void)setupProgressView {
    self.progressProxy = [[EUPageJumpWebViewProgress alloc] init];
    self.progressProxy.webViewProxyDelegate = self;
    self.progressProxy.progressDelegate = self;
    CGFloat progressBarHeight = 3.f;
    CGRect navigaitonBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, 0, navigaitonBarBounds.size.width, progressBarHeight);
    self.progressView = [[EUPageJumpWebViewProgressView alloc] initWithFrame:barFrame];
    self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.progressView setProgress:0.0];
    [self.view addSubview:_progressView];
    self.webView.delegate = self.progressProxy;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [super webViewDidFinishLoad:webView];
    //添加调试脚本库
    if (debugDelegate && [debugDelegate respondsToSelector:@selector(shoudlInjectDebugGapJS:)]) {
        if ([debugDelegate shoudlInjectDebugGapJS:self]) {
            NSString *debugGapInjectJSString =
                [NSString stringWithFormat:@"javascript:(function(e){e.setAttribute(\"src\",\"%@\");document.getElementsByTagName(\"body\")[0].appendChild(e);}"
                                           @")(document.createElement(\"script\"));void(0);",
                                           @"debuggap.js"];
            [self.commandDelegate evalJs:debugGapInjectJSString];
        }
    }

    if (debugDelegate && [debugDelegate respondsToSelector:@selector(shouldInjectWeinreJS:)] && [debugDelegate respondsToSelector:@selector(weireJSURL:)]) {
        if ([debugDelegate shouldInjectWeinreJS:self]) {
            NSString *weinreJSURL = [debugDelegate weireJSURL:self];
            NSString *jsString = [NSString stringWithFormat:@"javascript:(function(e){e.setAttribute(\"src\",\"%@\");document.getElementsByTagName(\"body\")[0]"
                                                            @".appendChild(e);})(document.createElement(\"script\"));void(0);",
                                                            weinreJSURL];
            [self.commandDelegate evalJs:jsString];
        }
    }
}

//在现有cordova只关心整个程序的生命周期。EUFramework的扩展版cordova.js增加对vc生命周期的监听
#pragma mark - entend cordova life cycle
- (void)fireCordovaViewWillAppear:(BOOL)animated {
    [self.commandDelegate evalJs:@"cordova.fireDocumentEvent('willappear');"];
}

- (void)fireCordovaWillDisappear:(BOOL)animated {
    [self.commandDelegate evalJs:@"cordova.fireDocumentEvent('willdisappear');"];
}

- (void)onNextPageClose {
    NSString *className = NSStringFromClass([EUPageJump class]);
    EUPageJump *pageJumpPlugin = [self.pluginObjects valueForKey:className];
    if (pageJumpPlugin) {
        [pageJumpPlugin onNextPageClose];
    }
}
- (void)reloadWebView {
    [self.webView reload];
}
#pragma mark - NJKWebViewProgressDelegate
- (void)webViewProgress:(EUPageJumpWebViewProgress *)webViewProgress updateProgress:(float)progress {
    // NSLog(@"progress:%f",progress);
    if (self.progressView) {
        [self.progressView setProgress:progress animated:YES];
    }
}

@end

@implementation EUPageJumpCommandDelegate

/* To override the methods, uncomment the line in the init function(s)
 in EUBasicViewController.h
 */

#pragma mark CDVCommandDelegate implementation

- (id)getCommandInstance:(NSString *)className {
    return [super getCommandInstance:className];
}

- (NSString *)pathForResource:(NSString *)resourcepath {
    return [super pathForResource:resourcepath];
}

@end

@implementation EUPageJumpCommandQueue

/* To override, uncomment the line in the init function(s)
 in EUBasicViewController.h
 */
- (BOOL)execute:(CDVInvokedUrlCommand *)command {
    return [super execute:command];
}

@end
